package com.god.gl.ble;

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.god.gl.ble.adapter.MyBluetoothAdapter;
import com.god.gl.ble.utils.HidConncetUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * @author gl
 * @date 2021/1/25
 * @desc
 */
public class BlueActivity extends AppCompatActivity {

    private static final String TAG = "BlueActivity";
    private BluetoothAdapter mBluetoothAdapter;
    private HidConncetUtil mHidConncetUtil;
    private BlueBroadcastReceiver mBlueBroadcastReceiver;
    private MyBluetoothAdapter mMyBluetoothAdapter;
    private ListView mListView;
    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue);
        checkPermissions();
        initview();
        initBlue();
        //初始化已连接hid列表
        initPair();
    }

    private void initview() {
        mListView = (ListView) findViewById(R.id.listview);
        Button search = (Button) findViewById(R.id.search);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //扫描蓝牙设备
                if (!mBluetoothAdapter.isDiscovering()) {
                    mBluetoothAdapter.startDiscovery();
                }
            }
        });
    }

    private void initPair() {
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "不支持蓝牙功能", Toast.LENGTH_LONG).show();
            //不支持蓝牙
            return;
        }
        //得到已经配对的列表
        Set<BluetoothDevice> mSet = mBluetoothAdapter.getBondedDevices();
        final Iterator mIterator = mSet.iterator();
        while (mIterator.hasNext()) {
            BluetoothDevice mBluetoothDevice = (BluetoothDevice) mIterator.next();



            if (mMyBluetoothAdapter == null) {
                mMyBluetoothAdapter = new MyBluetoothAdapter(BlueActivity.this);
                mListView.setAdapter(mMyBluetoothAdapter);
            }
            mMyBluetoothAdapter.addData(mBluetoothDevice);
            mMyBluetoothAdapter.notifyDataSetChanged();
        }
    }

    private void initBlue() {
        //初始化广播接收
        mBlueBroadcastReceiver = new BlueBroadcastReceiver();
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "不支持蓝牙功能", Toast.LENGTH_LONG).show();
            //不支持蓝牙
            return;
        }
        //如果没有打开蓝牙
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
        //4.0以上才支持HID模式
        if (Build.VERSION.SDK_INT >= 14) {
            this.mHidConncetUtil = new HidConncetUtil(this);
        }
    }



    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        this.unregisterReceiver(mBlueBroadcastReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBluetoothAdapter.isDiscovering()) {
            Log.e("onDestroy", "cancelDiscovery");
            mBluetoothAdapter.cancelDiscovery();
        }

    }

    public void registerReceiver() {
        IntentFilter localIntentFilter = new IntentFilter();
        localIntentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        localIntentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        localIntentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        localIntentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        localIntentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        localIntentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        localIntentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
     //   localIntentFilter.addAction("android.bluetooth.input.profile.action.CONNECTION_STATE_CHANGED");
        this.registerReceiver(mBlueBroadcastReceiver, localIntentFilter);
    }

    private class BlueBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String str = intent.getAction();
            Log.e(TAG, "onReceive" + str);
            //通过广播接收到了BluetoothDevice
            final BluetoothDevice localBluetoothDevice = (BluetoothDevice) intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (localBluetoothDevice != null) {
                Log.e(TAG, localBluetoothDevice.getName() + "=======" + localBluetoothDevice.getAddress());
                if (mMyBluetoothAdapter == null) {
                    mMyBluetoothAdapter = new MyBluetoothAdapter(BlueActivity.this);
                    mListView.setAdapter(mMyBluetoothAdapter);
                }
                mMyBluetoothAdapter.addData(localBluetoothDevice);
                mMyBluetoothAdapter.notifyDataSetChanged();
            }
        }
    }


    private void checkPermissions() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            Toast.makeText(this, getString(R.string.please_open_blue), Toast.LENGTH_LONG).show();
            return;
        }

        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                Log.d("permission","权限申请成功");
//                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
                onPermissionGranted(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M /*&& !checkGPSIsOpen()*/) {
                    new AlertDialog.Builder(this)
                            .setTitle(R.string.notifyTitle)
                            .setMessage(R.string.gpsNotifyMsg)
                            .setNegativeButton(R.string.cancel,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    })
                            .setPositiveButton(R.string.setting,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                                        }
                                    })

                            .setCancelable(false)
                            .show();
                }
                break;
        }
    }

    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OPEN_GPS) {
            if (checkGPSIsOpen()) {

            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.e("keyCode", keyCode + "");
        return super.onKeyDown(keyCode, event);
    }


}
